library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use WORK.COMMON.ALL;

entity GenTrunk is
port (
	CLK_MAIN, CLK_11, CLK_25, CLK_100, RST: in std_logic;
	E: in std_logic; -- 生成使能，1有效,ACK
	CMD_RESTART: in std_logic;
	NEW_TRUNK: out ITrunk -- 生成的树干，当E为0时输出无效
);
end GenTrunk;

architecture GenTrunk_bhv of GenTrunk is
	signal INDEX: std_logic_vector(20 downto 0);
	signal TIMER: std_logic_vector(31 downto 0);
begin
	process(INDEX, TIMER, CLK_25)
		variable iindex, itime:integer;
	begin
		iindex := CONV_INTEGER(INDEX) MOD 2;
		itime := CONV_INTEGER(TIMER) MOD 6;

		if CLK_25'Event and CLK_25='1' then
			if iindex = 0 then
				NEW_TRUNK <= TRUNK_N;
			else
				if itime = 0 OR itime = 1 then
					NEW_TRUNK <= TRUNK_L;
				elsif itime = 2 then
					NEW_TRUNK <= TRUNK_DL;
				elsif itime = 3 OR itime = 4 then
					NEW_TRUNK <= TRUNK_R;
				elsif itime = 5 then
					NEW_TRUNK <= TRUNK_DR;
				end if;
			end if;
		end if;
	end process;
	
	process(CLK_11)
	begin
		if CLK_11'Event AND CLK_11='1' AND CLK_100='1' then
			TIMER <= TIMER + 1;
		end if;
	end process;
	
	process(CLK_MAIN, RST)
	begin
		if RST='1' then
			INDEX <= (others => '0');
		elsif CLK_MAIN'event and CLK_MAIN='1' then
			if CMD_RESTART = '1' then
				INDEX <= (others => '0');
			elsif E = '1' then
				INDEX <= INDEX + 1;
			else
				INDEX <= INDEX;
			end if;
		end if;
	end process;
end GenTrunk_bhv;
